﻿

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using Playkanaler.WebPageSource;
using Playkanaler.WebPageSource.HtmlParser;


namespace Playkanaler.Channels.Svt
{

    public class SvtStartSetting : SvtSetting
    {
        public SvtStartSetting()
        {
            AddTabFromPage(new SvtPage() { Url = "http://svtplay.se/kategorier" }, "Kategorier");

            AddTabsFromPage(new SvtPage() { Url = "http://svtplay.se/" });          
           
        }
    }

    public class SvtSetting : SettingFromWeb
    {
        public SvtSetting()
        {                      
            View =  new EpView();          
  
            LoadingDone += new EventHandler<PageLoadedEventArg>(SvtSetting_LoadingDone);                        
        }

        void SvtSetting_LoadingDone(object sender, PageLoadedEventArg e)
        {
            if (((SvtPage)e.Page).sports.Count > 0)
            {
                TabFromWeb tab = new TabFromWeb("Sporter", Tabs.Count);
                tab.AddItemFromPageLinks(((SvtPage)e.Page).sports);
                tab.View = new ListView();
                Tabs.Add(tab);
            }
        }
        
        public override void ClickItem(Item item)
        {
            SvtSetting ny = new SvtSetting();
            ny.Heading = item.Title;
            ny.Page = new SvtPage() { Url = item.Path };            
            ny.Page.Load();


            bool videoAvailable = false;
            if (ny.Page.VideoTitle != null && ny.Page.VideoUrl != null && ny.Page.VideoUrl != "")
            {
                string mt = ny.Page.VideoTitle;
                if (item.Title.Contains("..."))
                {
                    mt = mt.Remove(item.Title.IndexOf("...")) + "...";
                }

                if (item.Title.EndsWith(mt))
                {
                    videoAvailable = true;                   
                }
            }


            if (videoAvailable)
            {
                playVideo(ny.Page.VideoUrl);
            }
            else
            {
                ny.Navigate();

                ny.LoadingDone += new EventHandler<PageLoadedEventArg>(delegate
                {
                    if (item.Attributes.ContainsKey("folder"))
                    {
                        ny.SelectedTabIndex = SelectedTabIndex;
                    }

                });
            }            

        }
        void playVideo(string url)
        {  
            string nyurl = string.Format("http://svt.se/svt/road/Classic/shared/flash/VideoPlayer/svtplayer-2010.2.swf?{0}&autostart=true", url);

            nyurl = new Uri(nyurl).AbsoluteUri;

            Microsoft.MediaCenter.Hosting.AddInHost.Current.MediaCenterEnvironment.NavigateToPage(Microsoft.MediaCenter.PageId.ExtensibilityUrl, nyurl);
            
            Settings.WriteReg("lasturl", nyurl);
           
        }      
    }

    public class SvtPage : BasicPage
    {
        const string cat="http://svtplay.se/kategorier";
        
        public List<PageLink> sports = new List<PageLink>();
        
        HtmlDoc doc;
        bool isCategoryPage;
        Tag browserTag;
        string browserTagId;


        protected override bool LoadPage()
        {



            WebClient wc = new WebClient();
            wc.Encoding = UTF8Encoding.UTF8;
            wc.Headers.Add("User-Agent", "Mozilla/4.0+");

            string dlstr = wc.DownloadString(Url);

            doc = new HtmlDoc();
            doc.Parse(dlstr);
            doc.CreateTree();



            isCategoryPage = (Url == cat);
            


            findBrowserTag();

            parsePlayerAndSports();

            parseTabs();

            parseContent();

            parsePaginationAndSetTemplate();
            


            return true;


        }








        void parsePlayer(Tag dividplayer)
        {
            VideoTitle = dividplayer
                .Child("div", "class", "layer")
                 .Child("div", "class", "info")
                  .Child("ul")
                   .Child("li", null)
                    .Child("h2").text;

            VideoUrl = dividplayer
                .Child("div", "class", "layer")
                 .Child("div", "class", "video")
                  .Child("object")
                   .Child("param", "name","flashvars")
                    .attribute["value"];


        }
        void addSports(Tag ul)
        {
            foreach (var li in ul.Children().Reverse<Tag>())
            {
                var a = li.Child("a");
                if (a.attribute["href"] == "#")
                {
                    addSports(li.Child("ul"));
                    continue;
                }
                PageLink pl = new PageLink();
                pl.name = a.text;
                pl.url = FixUrl(a.attribute["href"]);
                sports.Add(pl);
            }
        }

        void findBrowserTag()
        {
            var divrow = doc.Root
              .Child("body")
               .Child("div", "id", "wrapper")
                .Children("div");


            foreach (var row in divrow)
            {
                if (isCategoryPage)
                {
                    if (row.attribute["id"] == "categorylist")
                    {
                        browserTag = row;
                        break;
                    }
                }
                else
                {
                    if (row.attribute["id"].Contains("sb"))
                    {
                        browserTagId = "sb";
                        browserTag = row;
                        break;
                    }
                }
            }
            if (browserTag == null)
            {
                foreach (var row in divrow)
                {
                    if (row.attribute["id"].Contains("pb"))
                    {
                        browserTagId = "pb";
                        browserTag = row;
                        break;
                    }

                }
            }

        }



        void parsePlayerAndSports()
        {
            var divrow = doc.Root
               .Child("body")
                .Child("div", "id", "wrapper")
                 .Children("div");



            //sports & player
            foreach (var row in divrow)
            {
                if (row.attribute["id"] == "bs")
                {
                    var ul = row.Child("div").Child("ul");
                    addSports(ul);
                }
                if (row.attribute["id"] == "player")
                {
                    parsePlayer(row);
                }

            }
        }



        void parseTabs()
        {
            Tag tabsul = null;
            foreach (Tag t in browserTag.Children("div"))
            {
                if (t.attribute["class"].Contains("navigation"))
                {
                    tabsul = t.Child("ul");
                    break;
                }
            }

            if (tabsul != null)
            {

                foreach (var li in tabsul.Children())
                {
                    PageLink pl = new PageLink();
                    pl.selected = (li.attribute["class"] == "selected");
                    Tag a = null;
                    if (pl.selected)
                    {
                        a = li.Child("h2").Child("a");
                    }
                    else
                    {
                        a = li.Child("a");
                    }
                    pl.name = a.text;
                    pl.url = FixUrl(a.attribute["href"]);
                    Tabs.Add(pl);
                }
            }
            else
            {
                Tabs.Add(new PageLink("Alla") { selected = true });
            }
            Tabs.Reverse();
        }




        void parseContent()
        {
            // parse content
            var uls = browserTag
                .Child("div", "class", "content")
                 .Child("div")
                  .Child("div")
                   .Child("div", "class", "tab active")
                    .Children("ul");

            foreach (var ul in uls)
            {
                foreach (var li in ul.Children())
                {
                    if (li.attribute["class"] == "error") continue;
                    PageLink pl = new PageLink();
                    if (isCategoryPage)
                    {
                        var a = li.Child("div").Child("a");
                        pl.imageurl = FixUrl(a.Child("img").attribute["src"]);
                        pl.name = a.Child("span", "class", "category-header").text;
                        pl.url = FixUrl(a.attribute["href"]);
                        // pl.description = a.text;
                    }
                    else
                    {
                        var a = li.Child("a");

                        pl.imageurl = FixUrl(a.Child("img").attribute["src"]);
                        if (a.attribute["class"].Contains("folder"))
                        {
                            pl.data["folder"] = true;
                        }
                        pl.name = a.Child("span").text;
                        pl.url = FixUrl(a.attribute["href"]);
                        pl.description = a.text;
                    }
                    Items.Add(pl);
                }
            }
            Items.Reverse();
        }




        void parsePaginationAndSetTemplate()
        {
            if (browserTag.Child("div", "class", "footer").Child("div", "class", "pagination").HasChild("ul"))
            {
                var lis = browserTag.Child("div", "class", "footer").Child("div", "class", "pagination").Child("ul").Children("li", "class", "");
                if (lis.Count > 0)
                {

                    var an = lis.First().Child("a");
                    NumContentPages = int.Parse(an.text) + 1;
                    string temp = an.attribute["href"].Substring(1);
                    string[] brws = temp.Split('/');

                    string ny = "?";

                    foreach (string brw in brws)
                    {
                        if (brw.StartsWith(browserTagId))
                        {
                            string[] part = brw.Split(',');
                            part[2] = "{PageNumber}";
                            ny += string.Join(",", part);
                        }
                        else
                        {
                            ny += brw;
                        }
                        if (brw != brws.Last()) ny += "/";
                    }
                    ContentPageNavTemplateReplaceStr = "{PageNumber}";
                    ContentPageNavTemplate = FixUrl(ny);
                    NumContentPagesLoaded = 1;
                }

            }
            else NumContentPages = 0;
        }
    }
}